package cn.itcast.sys.service.impl;


import cn.itcast.orders.feign.OrderFegin;
import cn.itcast.orders.pojo.Orders;
import cn.itcast.orders.vo.OrderReportVO;
import cn.itcast.sys.service.ReportService;
import cn.itcast.sys.service.WorkspaceService;
import cn.itcast.sys.vo.BusinessDataVO;
import cn.itcast.sys.vo.SalesTop10ReportVO;
import cn.itcast.sys.vo.TurnoverReportVO;
import cn.itcast.users.feign.UserFegin;
import cn.itcast.users.vo.UserReportVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    /**
     * 这里不使用Servate
     * 因为这是数据统计按理来说应该应该使用的是其他业务层的Mapper
     *
     */
//    @Autowired
//    private OrderMapper orderMapper;
//    @Autowired
//    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Autowired
    private OrderFegin orderFegin;
    @Autowired
    private UserFegin userFegin;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverReportVO(LocalDate begin, LocalDate end) {
        List<String> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();

        LocalDateTime startTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        while (!startTime.isAfter(endTime)){
            Map<String, Object> map = new HashMap<>();
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            map.put("status",5);

//            Double number = orderMapper.sumByMap(map);
            Double number = orderFegin.sumByMap(map);

            dateList.add(startTime.toString());
            turnoverList.add(number==null?0:number);

            startTime = startTime.plusDays(1);
        }
        String list = StringUtils.join(dateList, ',');
        String doubList = StringUtils.join(turnoverList, ',');

        return TurnoverReportVO.builder()
                .dateList(list)
                .turnoverList(doubList)
                .build();
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        while( !begin.isAfter(end) ){
            LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MAX);
            LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MIN);
            Map<String, Object> map = new HashMap<>();
            map.put("endTime",endTime);
            //算出总用户量
//            Integer userCount = userMapper.countByMap(map);
            Integer userCount = userFegin.countByMap(map);

            map.put("beginTime",beginTime);
            //算出新用户
//            Integer newUserCount = userMapper.countByMap(map);
            Integer newUserCount = userFegin.countByMap(map);

            newUserList.add(newUserCount);
            totalUserList.add(userCount);
            dateList.add(begin);

            begin = begin.plusDays(1);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>(); //订单
        List<Integer> validOrderCountList = new ArrayList<>(); //有效

        while ( !begin.isAfter(end) ){
            LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin,LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
//            Integer validOrderCount = orderMapper.countByMap(map);
            Integer validOrderCount = userFegin.countByMap(map);

            map.put("status", Orders.COMPLETED);
//            Integer totalOrderCount = orderMapper.countByMap(map);
            Integer totalOrderCount = userFegin.countByMap(map);

            dateList.add(begin);
            orderCountList.add(validOrderCount);
            validOrderCountList.add(totalOrderCount);

            begin = begin.plusDays(1);
        }
        Integer totalOrderCount = orderCountList.stream().mapToInt(o->o).sum();
        Integer validOrderCount = validOrderCountList.stream().mapToInt(o->o).sum();
        Double orderCompletionRate = (validOrderCount * 1.0)/totalOrderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        //商品名称列表，以逗号分隔 销量列表，以逗号分隔
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        Map<String, Object> map = new HashMap<>();
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status",Orders.COMPLETED);


//        List<Map<String, Object>> list = orderMapper.getTop10ByMap(map);
        List<Map<String, Object>> list = orderFegin.getTop10ByMap(map);


        list.forEach(o->{
            nameList.add(o.get("name")+"");
            numberList.add(Integer.valueOf(o.get("number")+""));
        });

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出Excel报表接口
     *
     * @param response
     */
    @SneakyThrows
    @Override
    public void export(HttpServletResponse response) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("temaplate/运营数据报表模板.xlsx");
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
        LocalDate now = LocalDate.now();
        LocalDateTime begin = LocalDateTime.of(now.plusDays(-30),LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(now.plusDays(-1),LocalTime.MAX);

        //准备数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        //开写
        sheet.getRow(1).getCell(1).setCellValue(begin.toLocalDate().toString()+"至"+end.toLocalDate());
        XSSFRow row3 = sheet.getRow(3);
        row3.getCell(2).setCellValue(businessData.getTurnover());
        row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row3.getCell(6).setCellValue(businessData.getNewUsers());

        XSSFRow row4 = sheet.getRow(4);
        row4.getCell(2).setCellValue(businessData.getValidOrderCount());
        row4.getCell(4).setCellValue(businessData.getUnitPrice());


        for (int i = 0; i < 30; i++) {
            LocalDate date = LocalDate.now().plusDays(0-i);
            BusinessDataVO loopPusinessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date,LocalTime.MAX));
            XSSFRow row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(loopPusinessData.getTurnover());
            row.getCell(3).setCellValue(loopPusinessData.getValidOrderCount());
            row.getCell(4).setCellValue(loopPusinessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(loopPusinessData.getUnitPrice());
            row.getCell(6).setCellValue(loopPusinessData.getNewUsers());
        }
        ServletOutputStream outputStream = response.getOutputStream();
        xssfWorkbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        inputStream.close();
        xssfWorkbook.close();
    }



////        getTurnoverReportVO();
//        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("temaplate/运营数据报表模板.xlsx");
//        LocalDate localDate = LocalDate.now().plusDays(-31);
//
//        LocalDate begin = LocalDate.now().plusDays(-31);
//        LocalDate end = LocalDate.now().plusDays(-1);
//        getTurnoverReportVO(begin,end);
//
//        //获取数据
//        TurnoverReportVO turnoverReport = getTurnoverReportVO(begin, end);
//        OrderReportVO orderReport = getOrdersStatistics(begin, end);
//        UserReportVO userReport = getUserStatistics(begin, end);
//
//        //与表建立连接
//        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
//        XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
//        sheetAt.getRow(1).getCell(1).setCellValue(begin + "至" + end);
//        XSSFRow row3 = sheetAt.getRow(3);
//        row3.getCell(2).setCellValue(turnoverReport.getTurnoverList());
//        row3.getCell(4).setCellValue(orderReport.getValidOrderCount());
//        row3.getCell(6).setCellValue(userReport.getNewUserList());
//
//        XSSFRow row4 = sheetAt.getRow(4);
//        row4.getCell(2).setCellValue(orderReport.getValidOrderCount());
//        row4.getCell(4).setCellValue(11 / 10);
//
//        for (int i = 0; i < 30; i++) {
//            TurnoverReportVO t = getTurnoverReportVO(begin, end);
//            OrderReportVO o = getOrdersStatistics(begin, end);
//            UserReportVO u = getUserStatistics(begin, end);
//
//            begin.plusDays(i);
//            XSSFRow row = sheetAt.getRow(7 + i);
//            row.getCell(1).setCellValue(begin + "");
//            row.getCell(2).setCellValue(t.getTurnoverList());
//            row.getCell(3).setCellValue(o.getTotalOrderCount());
//            row.getCell(4).setCellValue(o.getOrderCompletionRate());
//            row.getCell(5).setCellValue(1.2);
//            //Double.valueOf(t.getTurnoverList()) / Integer.valueOf(u.getNewUserList())
//            row.getCell(6).setCellValue(u.getNewUserList());
//        }
//        OutputStream outputStream = response.getOutputStream();
//        xssfWorkbook.write(outputStream);
//        outputStream.flush();
//        outputStream.close();
//        inputStream.close();
//        xssfWorkbook.close();

}
